package controller;

import java.util.ArrayList;
import java.util.regex.Pattern;

import dal.datastore.TableData;

/**
 * @author Stanley
 *
 */
public class SELECTCommand {
	private String _command;
	private TableData _data;

	public SELECTCommand(String _command, TableData _data) {
		super();
		this._command = _command;
		this._data = _data;
	}

	public SELECTCommand(String _command) {
		super();
		this._command = _command;
	}

	/**
	 * Execute select command
	 * @return TableData
	 * @throws Exception 
	 */
	public TableData execute() throws Exception {
		if (isSelectCommand()) {
			if (_command.equalsIgnoreCase("*")) {
				return _data;
			} else {
				ArrayList<String> cols = parseCommand();
				return _data.selectDataWithColumns(cols);				
			}
		}
		return null;
	}

	private boolean isSelectCommand() {
		String pattern = "(\\*|(\\s*\\w+\\s*(,\\s*\\w+\\s*)*)|(\\s*\\w+.\\w+\\s*(,\\s*\\w.\\w+\\s*)*))";
		return _command.matches(pattern);
	}
	
	private ArrayList<String> parseCommand(){
		Pattern p = Pattern.compile(",");
		String[] strings  = p.split(_command);
		return QueryParser.removeAllEmptyString(strings);
	}

	public String getCommand() {
		return _command;
	}

	public void setCommand(String _command) {
		this._command = _command;
	}
}
